<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2023/3/13
 * Time: 11:16
 */

namespace App\Rep;


use App\Exceptions\ApiException;
use App\Models\Employee;
use App\Models\EmployeeJobType;
use App\Models\JobType;
use App\Models\ModelNumberSpecification;
use App\Models\ModelNumberUser;
use App\Models\Order;
use App\Models\OrderChild;
use App\Models\Rbac\User;
use App\Models\UserJobType;
use Illuminate\Support\Facades\DB;



class EmployeeRep
{
    /**
     * 获取员工列表
     * @param $params
     * @return mixed
     */
    public function getEmployeeListRep($params){
        $params['roles_id'] = 16;
        //$list = User::Search($params)->with(['employee','role'])->orderBy('id','desc')->paginate($params['per_page']??10);
        $list = Employee::Search($params)
            ->with(['user'=>function($q){
                $q->with(['role','job_type']);
            }])
            ->orderBy('job_type_id','desc')->paginate($params['per_page']??10);
        return $list;
    }

    /**
     * 清空员工卡号
     * @param $params
     * @return void
     */
    public function clearEmployeeCardIdRep($params){
        $model = Employee::whereIn('user_id',$params['users_ids'])->update(['card_number'=>'']);
//        $model->card_number = '';
//        $model->save();
        return $model;
    }

    /**
     * 添加员工
     * @param $params
     * @return Employee|array
     */
    public function createEmployeeRep($params){
        DB::beginTransaction();
        try{
            $user = User::find($params['users_id']);
            if(isset($params['id']) && !empty($params['id'])){
                $model = Employee::find($params['id']);
            }else{
                $model = new Employee();
                $res = Employee::where('is_del',2)->where('user_id',$params['users_id'])->first();
                if($res){
                    throw new ApiException(20001,'当前账号已绑定员工');
                }
            }
            $model->employee_name = $user->company_name;
            $model->user_id=$params['users_id'];
            $model->phone = $params['phones']??"";
            $model->address = $params['address']??'';
            //$model->job_type_id = $params['job_type_id'];
            $model->id_card = $params['id_card']??'';
            $model->native_place = $params['native_place']??'';
            $model->emergency_contact = $params['emergency_contact']??'';
            $model->emergency_contact_phone = $params['emergency_contact_phone']??'';
            $model->card_number = $params['card_number']??null;
            $model->base_pay = $params['base_pay']??'';
            if(!empty($params['hiredate'])){
                $model->hiredate = $params['hiredate']??'';
            }
            $model->submit_way = $params['submit_way'];
            $model->level = $params['level']??'';
            $model->is_del=2;
            $model->save();
            $data = User::with(['role','employee'])->find($model->user_id);
            UserJobType::where('user_id',$user->id)->delete();
            foreach($params['job_type_arr'] as $k=>$v){
                UserJobType::updateOrCreate(
                    ['user_id'=>$user->id,'job_type_id'=>$v],
                    ['user_id'=>$user->id,'job_type_id'=>$v]
                );
            }
            DB::commit();
            return ['code'=>0,'data'=>$data,'msg'=>''];
        }catch(\Exception $e){
            DB::rollBack();
            return ['code'=>2001,'data'=>[],'msg'=>$e->getMessage()];
        }
    }





    /**
     * 删除员工
     * @param $params
     */
    public function delEmployeeRep($params){
        try {
            DB::beginTransaction();
            $model = Employee::where('id',$params['id'])->first();
            User::where('id',$model->user_id)->update(['is_del'=>1]);
            $model->is_del = $params['is_del']??1;
            $model->save();
            DB::commit();
            return $model;
        }catch(\Exception $exception){
            DB::rollBack();
            return ['code'=>2001,'data'=>[],'msg'=>$exception->getMessage()];
        }

    }

    /**
     * 根据type_job_id获取员工列表
     * @param $params
     */
    public function getEmployeeListByJobTypeIDRep($params){
        return Employee::where('is_del',2)->where('job_type_id',$params['job_type_id'])->get();
    }

    /**
     * 查询员工可领取订单
     * 1.指派的订单
     * 2.工种未领取的订单
     * 备注：排序按派单顺序设置
     * 工种可领几条数据就显示几条数据
     */
    public function searchPensionableOrderChildRep($params){
        $employee_user_id = $params['user_id'];
        $job_type_id = $params['job_type_id'];
        $employeeInfo = $this->setEmployeeInfo($params['user_id'],$job_type_id);
        //p($employeeInfo);
        if($employeeInfo['unclaimed_num']<=0){
            return ['code'=>1017,'data'=>[],'msg'=>'不可领取多个工单!unclaimed_num='.$employeeInfo['unclaimed_num'].";already_received_num=".$employeeInfo['already_received_num']];
        }
        //$job_type_id = $this->getJobTypeIdByEmployeeUserId($employee_user_id);
        $orderByArr = (new DispatchOrderRep())->getDispatchOrderSortRep();
        //开启执行日志
        //DB::connection()->enableQueryLog();

        $query = OrderChild::where('order_child.is_del',"<>",1)->where('order.status',1)
            ->where(function($q)use($employee_user_id,$job_type_id){
                $q->orwhere(function($q)use($employee_user_id){
                    //指派
                    $q->where('order_child.status',3)
                        ->where('order_child.employee_user_id',$employee_user_id)
                        ->where('order_child.is_appoint',1);
                })->orwhere(function($q)use($job_type_id){
                    $q->where('order_child.job_type_id',$job_type_id)
                        ->where('order_child.is_epiboly',2)//是否外包
                        ->where('order_child.is_appoint',2)//是否指派
                        ->where('order_child.status',3);
                });
            })
            ->join('order', 'order.id', '=', 'order_child.order_id')
            ->select(
                'order_child.*',
                'order.id as orders_id',
                'order.color_id',
                'order.customer_id',
                'order.model_number_id',
                'order.product_id',
                'order.status')
            ->orderBy($orderByArr[0]['field_name'],$orderByArr[0]['sortord'])
            ->orderBy($orderByArr[1]['field_name'],$orderByArr[1]['sortord'])
            ->orderBy($orderByArr[2]['field_name'],$orderByArr[2]['sortord'])
            ->orderBy($orderByArr[3]['field_name'],$orderByArr[3]['sortord']);
        $query->with(['order_second']);
        //$query->orderBy('product_num','asc');
        $list = $query->get();
        //p($list->toArray());
        $order_child_ids = [];
        foreach($list as $k=>$v){

            $jobTypeRep = new JobTypeRep();
            if($v->is_appoint == 2){
                //关联工人判断
                $model_number_id = Order::where('id',$v->order_id)->value('model_number_id');
                $model_number_user_id_arr = ModelNumberUser::where('model_number_id',$model_number_id)
                    ->where('job_type_id',$job_type_id)
                    ->where('user_id','<>',0)
                    ->pluck('user_id')
                    ->toArray();
                if(!empty($model_number_user_id_arr)){
                    if(!in_array($employee_user_id,$model_number_user_id_arr)){
                        continue;
                    }
                }
            }
            //产品是否关联了工种
            $ProductJobType = $jobTypeRep->getProductJobTypeRep($v->job_type_id,$v->product_id);
            if(!$ProductJobType){
                continue;
            }
            //是否限制流程
            $is_restrict = $jobTypeRep->judgeIsRestrict($ProductJobType);
            if($is_restrict){
                //限制流程，判断上个工序是否完成
                $res = $this->judgeLastProcess($v->order_id,$v->product_num,$ProductJobType);
                //p($res);
                if(!$res){
                    //return ['code'=>1018,'data'=>[],'msg'=>'限制流程，有尚未完成的工序'];
                    continue;
                }
            }
            $order_child_ids[] = $v->id;
            //p1('循环结束');
        }
        //p($order_child_ids);
        if(!empty($order_child_ids)){
            //array_splice:从数组中移除元素，并用新元素取代它：
            $order_child_ids = array_splice($order_child_ids,0,$employeeInfo['unclaimed_num']);
        }
        $list = OrderChild::whereIn('id',$order_child_ids)
            ->with(['order'=>function($q){
                $q->with(['color'=>function($q){
                    return $q->select('id','color');
                },'product'=>function($q){
                    return $q->select('id','product_name');
                },'customer'=>function($q){
                    return $q->select('id','customer_name','customer_address','balance','contact_phone');
                },'modelNumber'=>function($q){
                    return $q->select('id','model_number','file_id')->with(['specification','file']);
                },'orderChild'=>function($q){
                    return $q->with(['job_type','employee']);
                },'specification'=>function($q){
                    return $q->select('id','specification');
                }]);
            }])
            ->with(['job_type'])
            ->select('order_second_id','order_id','job_type_id',DB::raw('count(*) as order_count'))
            ->groupBy('order_id')->get()->toArray();



        return $list;
    }

    /**
     * 获取员工的工种id
     * @param $employee_user_id
     * @return $job_type_id
     */
    public function getJobTypeIdByEmployeeUserId($employee_user_id){
        $employee = Employee::where('user_id',$employee_user_id)->first();
        return $employee->job_type_id;
    }

    /**
     * 员工领取订单
     * @param $params
     * user_id
     * order_child_id
     */
    public function drawOrderChildRep($params){
        $user_id = $params['user_id'];
        $job_type_id = $params['job_type_id'];
        $employeeInfo = $this->setEmployeeInfo($params['user_id'],$job_type_id);
        //p($employeeInfo);
        if($employeeInfo['unclaimed_num']<=0){
            throw new ApiException(1017,'不可领取多个工单');
            //return ['code'=>1017,'data'=>['data'=>[],'info'=>$employeeInfo],'msg'=>'不可领取多个工单'];
        }

        $query = OrderChild::query();
        $query->where('job_type_id',$params['job_type_id']);
        $query->where('status',3);
        //$query->where('order_second_id',$params['order_second_id']);
        $query->where('order_id',$params['order_id']);
        $query->where(function($q)use($user_id){
            $q->orwhere(function($q)use($user_id){
                //指派
                $q->where('employee_user_id',$user_id)
                    ->where('is_appoint',1);//指派
            })->orwhere(function($q){
                $q->where('is_epiboly',2)//是否外包
                ->where('is_appoint',2);//是否指派
            });
        });
        $query->orderBy('product_num','asc');
        //$query->limit($params['order_count']);
        $data = $query->with(['order','order_second'])->get();
        //p($data->toArray());
        $order_child_id_arr = [];
        foreach($data as $k=>$v){
            if(!empty($v->draw_time)){
                //return ['code'=>1023,'data'=>$employeeInfo,'msg'=>'该工单已领取，无需再次领取'];
                continue;
            }

            $jobTypeRep = new JobTypeRep();
            $ProductJobType = $jobTypeRep->getProductJobTypeRep($v->job_type_id,$v->order->product_id);
            if(!$ProductJobType){
                //未设置工序
                continue;
            }
            $is_restrict = $jobTypeRep->judgeIsRestrict($ProductJobType);
            if($is_restrict){
                //限制流程，判断上个工序是否完成
                $res = $this->judgeLastProcess($v->order_id,$v->product_num,$ProductJobType);
                if(!$res){
                    continue;
                }
            }
            if(count($order_child_id_arr)>$params['order_count']){
                continue;
            }
            $order_child_id_arr[] = $v->id;
//            $v->employee_user_id = $params['user_id'];
//            $v->draw_time = date("Y-m-d H:i:s",time());
//            $v->operator_user_id = $params['user_id'];
//            $v->status = 2;
//            $v->save();
        }
        //p($order_child_id_arr);
        if(empty($order_child_id_arr[0])){
            throw new ApiException(20001,'暂无可领取订单');
        }else{
            $order_child_id_arr = array_splice($order_child_id_arr,0,$employeeInfo['unclaimed_num']);
            OrderChild::whereIn('id',$order_child_id_arr)->update([
                'employee_user_id' => $params['user_id'],
                'draw_time' => date("Y-m-d H:i:s",time()),
                'operator_user_id' => $params['user_id'],
                'status' => 2
            ]);
        }
        $querys = OrderChild::query();
        $querys->where('id',$order_child_id_arr[0]);
        $order_child = $querys->with(['order'=>function($q){
            return $q->with(['customer','modelNumber','color','specification']);
        },'employee','job_type','order_second'=>function($q){
            $q->with(['product']);
        }])->first();


        return [
            'code'=>0,
            'data'=>[
                'data'=>$order_child,
                'count'=>count($order_child_id_arr),
                'order_child_id_arr'=>$order_child_id_arr
            ],'msg'=>'success'];
    }

    /**
     * 提交订单
     */
    public function submitOrderChildRep($params){
        $user_id = $params['employee_user_id']??$params['user_id'];
//        $employeeInfo = $this->setEmployeeInfo($user_id);
//        if($employeeInfo['unclaimed_num']<=0){
//            return ['code'=>1017,'data'=>$employeeInfo,'msg'=>'不可领取多个工单'];
//        }

        $order_child = OrderChild::whereIn('id',$params['order_child_ids'])->get();
        foreach($order_child as $k=>$v){
            $order = Order::find($v->order_id);
            //限制流程，判断上个工序是否完成
//            $res = $this->judgeLastProcess($v->order_id,$v->sort);
//            if(!$res){
//                return ['code'=>1018,'data'=>[],'msg'=>'限制流程，有尚未完成的工序'];
//            }
            if(empty($v->employee_user_id) && $v->appoint != 1){
                //continue;
                return ['code'=>1022,'data'=>[],'msg'=>'该工单未指派员工'];
            }
            if(!empty($v->submit_time) && $v->status = 1){
                continue;
                //return ['code'=>1022,'data'=>[],'msg'=>'该工单已提交，无需再次提交'];
            }
            if(empty($v->draw_time)){
                $v->draw_time = date("Y-m-d H:i:s",time());
            }
//            $ress = ModelNumberUser::where('model_number_id',$order->model_number_id)
//                ->where('job_type_id',$employeeInfo['job_type_id'])
//                ->where('user_id',$user_id)
//                ->first();
//            if(!$ress){
//                return ['code'=>1026,'data'=>[],'msg'=>'未关联型号，你无权领取当前订单'];
//            }
            $v->submit_time = date("Y-m-d H:i:s",time());
            $v->status = 1;
            if(!empty($params['image1']??'')){
                $v->image1 = $params['image1'];
            }
            if(!empty($params['image2']??'')){
                $v->image2 = $params['image2'];
            }
            if(!empty($params['image3']??'')){
                $v->image3 = $params['image3'];
            }
            if(!empty($params['image4']??'')){
                $v->image4 = $params['image4'];
            }
            $v->save();
            $orderRep = new OrderRep();
            //加入半成品库
            $orderRep->selectOrderChildStatusBySecondId($v->order_id,$v->order_second_id);
            //加入成品库
            $orderRep->selectOrderChildStatusByOrderId($v->order_id);
        }

        return ['code'=>0,'data'=>$order_child,'msg'=>'success'];
    }

    /**
     * 打印 提交订单
     */
    public function submitOrderChildByDayinRep($params){
        $order = Order::where('order_number',$params['order_number'])->first();
        if(!$order){
            return ['code'=>2003,'data'=>[],'msg'=>'订单号错误！'];
        }
        $order_child = OrderChild::where('order_id',$order->id)->where('employee_user_id',$params['employee_user_id'])->first();

        if(!empty($order_child->submit_time) && $order_child->status = 1){
            return ['code'=>1022,'data'=>[],'msg'=>'该工单已提交，无需再次提交'];
        }
        $order_child->submit_time = date("Y-m-d H:i:s",time());
        $order_child->status = 1;
        if(!empty($params['image1']??'')){
            $order_child->image1 = $params['image1'];
        }
        if(!empty($params['image2']??'')){
            $order_child->image2 = $params['image2'];
        }
        if(!empty($params['image3']??'')){
            $order_child->image3 = $params['image3'];
        }
        if(!empty($params['image4']??'')){
            $order_child->image4 = $params['image4'];
        }
        $order_child->save();
        $orderRep = new OrderRep();
        $orderRep->selectOrderChildStatusBySecondId($order_child->order_id,$order_child->order_second_id);
        //加入成品库
        $orderRep->selectOrderChildStatusByOrderId($order_child->order_id);
        return ['code'=>0,'data'=>$order_child,'msg'=>'success'];
    }





    /**
     * 查询【已完成/未完成】的订单
     * @param $params
     */
    public function searchCompletedOrUnfinishedOrderChildRep($params){
        $status = $params['status']??1;
        $model = OrderChild::where('employee_user_id',$params['user_id'])
            ->where('is_del','<>','1')
            ->where('job_type_id',$params['job_type_id'])
            ->with(['order'=>function($q){
            return $q->with(['customer','modelNumber','color','specification']);
        },'employee','job_type']);
        if($status == 1){
            $model->where('status',$status)->whereNotNull('submit_time');
                //->paginate($params['per_page']??10);
        }elseif($status == 2){
            $model->where('status',$status)->whereNull('submit_time');
                //->paginate($params['per_page']??10);
        }
        $order_child_ids = $model->pluck('id')->toArray();
        $list = OrderChild::whereIn('id',$order_child_ids)
            ->with(['order_second'=>function($q){
                 $q->with([
                     'model_number',
                     'color',
                     'specification',
                     'models'=>function($q){
                         $q->select('modelid','modelname');
                     },
                     'product'=>function($q){
                         $q->select('id','product_name');
                     }
                 ]);
            },
                'employee',
                'job_type',
                'order'=>function($q){
                    $q->select('id','customer_id','serial_number','order_number','order_date','product_id','model_number_id','specification_id')->with([
                        'customer'=>function($q){
                            $q->select('id','customer_name');
                        },'product','modelNumber','specification'
                    ]);
                }
            ])
            ->select('id','order_id','job_type_id',DB::raw('count(*) as order_count'))
            ->groupBy('order_id')->get()->toArray();
        foreach($list as $k=>$v){

            $order = Order::where('id',$v['order_id'])->first();
            $v['order']['emergency_procedure'] = $order['emergency_procedure'];
//            $image = ModelNumberSpecification::where('product_id',$order->product_id)
//                ->where('model_number_id',$order->model_number_id)
//                ->where('specification_id',$order->specification_id)
//                ->first();
//            $list[$k]['image'] = $image->image;


            $price = (new ProductRep())->getPriceByJobTypeId(
                $v['order']['product_id'],
                $v['order']['model_number_id'],
                $v['job_type_id'],
                $v['order']['specification_id']
            );
            $list[$k]['price'] = $price;
            $list[$k]['order_child_ids'] = OrderChild::whereIn('id',$order_child_ids)->where('order_id',$v['order_id'])->pluck('id')->toArray();
        }
        return $list;
    }

    /**
     * 判断上一个工序是否完成
     */
    public function judgeLastProcess($order_id,$product_num,$product_job_type){
        $pid = $product_job_type->pid;
        $pid_arr = explode(',',$pid);
        foreach($pid_arr as $v){
            if($v == 0){
                return true;
            }else{
                $count = OrderChild::where('order_id',$order_id)
                    ->where('product_num',$product_num)
                    ->where('job_type_id',$v)
                    ->where('status','<>',1)
                    ->count();
                //p($count);
                if($count > 0){
                    return false;
                }
            }
        }
//        $count = OrderChild::where('order_id',$order_id)
//            ->where('sort','<',$sort)
//            ->where('status','<>',1)
//            ->count();
//        if($count > 0){
//            return false;
//        }
        return true;
    }

    /**
     * 设置员工登录，员工基本信息
     * @param $user_id
     */
    public function setEmployeeInfo($user_id,$job_type_id=''){
        $employee = Employee::where('user_id',$user_id)
            ->with('job_type')
            ->first();
        //p($employee->toArray());
        $job_type = JobType::where('id',$job_type_id)->first();
        if($job_type_id==''){
            $arr['unclaimed_num'] = 0;
            $arr['multi_order_num'] = 0;
            $arr['already_received_num'] = 0;
            $arr['job_type_id'] = '';
            return $arr;
        }
        //p($job_type);
        //可领单数
        $arr['multi_order_num'] = 1;
        if($job_type->is_multi == 1){
            $arr['multi_order_num'] = $job_type->multi_order_num;
        }
        //已领单数
        $arr['already_received_num'] = OrderChild::where('status',2)
            ->where('employee_user_id',$user_id)
            ->where('is_del',2)
            ->count();
        //未领取数
        $arr['unclaimed_num'] = $arr['multi_order_num'] - $arr['already_received_num'];
        $arr['job_type_id'] = $employee->job_type_id;
        return $arr;
    }





}
